<template>
  <div class="checkout-address">
    <div class="text">
      <div v-if="!showAddress" class="none">您需要先添加收货地址才可提交订单。</div>
      <ul v-if="showAddress">
        <li><span>收<i />货<i />人：</span>{{ showAddress.receiver }}</li>
        <li><span>联系方式：</span>{{ showAddress.contact }}</li>
        <li><span>收货地址：</span>{{ showAddress.fullLocation.replace(/ /g, '') + showAddress.address }}</li>
      </ul>
      <a v-if="showAddress" href="javascript:;" @click="edit" >修改地址</a>
    </div>
    <div class="action">
      <el-button class="btn" @click="dialogVisible = true">切换地址</el-button>
      <el-button class="btn" @click="add">添加地址</el-button>
    </div>
    <!-- 切换收获地址  -->
    <el-dialog v-model="dialogVisible" title="切换收获地址" >
      <div @click="showDialogDiv = item.id" class="text item" :class="{dialogDiv: showDialogDiv ==  item.id}" v-for="item in list" :key="item.id">
        <ul>
          <li><span>收<i />货<i />人：</span>{{ item.receiver }}</li>
          <li><span>联系方式：</span>{{ item.contact }}</li>
          <li><span>收货地址：</span>{{ item.fullLocation.replace(/ /g, '') + item.address }}</li>
        </ul>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleOk">确定</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 添加-修改 -->
    <el-dialog v-model="addDialogVisible" :title="`${formData.id? '编辑' : '添加' }收获地址`" width="60%" @close="closeForm">
      <el-form ref="serviceForm" :model="formData" label-width="120px" width='600' :rules="formRule">
        <el-form-item label="收货人:" prop="receiver">
            <el-input size="large" v-model="formData.receiver" placeholder="请输入收货人" ></el-input>
        </el-form-item>
        <el-form-item label="手机号:" prop="contact">
          <el-input size="large" v-model="formData.contact" placeholder="请输入手机号" ></el-input>
        </el-form-item>
        <el-form-item label="地区:" prop="fullLocation">
            <xtx-city class="city" @change="changeCty" :fullLocation="formData.fullLocation || '请选择地区'"/>
        </el-form-item>
        <el-form-item label="详细地址:" prop="address">
          <el-input  size="large" v-model="formData.address" placeholder="请输入详细地址" ></el-input>
        </el-form-item>
        <el-form-item label="邮政编码:" prop="postalCode">
          <el-input size="large" v-model="formData.postalCode" placeholder="请输入邮政编码"></el-input>
        </el-form-item>
        <el-form-item label="地址标签:" prop="addressTags">
          <el-input  size="large" v-model="formData.addressTags" placeholder="请输入地址标签，逗号分隔"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleAddOk">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script>
import { reactive, ref, watch, onMounted } from 'vue';
import { addAddress, editAddress, findCheckoutInfo } from '@/api/order'
import { ElMessage } from 'element-plus'
export default {
  name: 'CheckoutAddress',
  props: {
    list: {
      type: Array,
      default: () => []
    }
  },
  setup(props, { emit }) {
    const showDialogDiv = ref(null)
    // 切换收获地址
    const dialogVisible = ref(false)
    // 显示的地址
    const showAddress = ref(null)
    watch(showAddress,(newVal)=>{
      emit('currAddress',newVal)
    })
    if (props.list.length) {
      const defaultAddress = props.list.find(item => item.isDefault === 1)
      if (defaultAddress) {
        showAddress.value = defaultAddress
      } else {
        showAddress.value = props.list[0]
      }
      showDialogDiv.value =  showAddress.value.id
    }
    // 选择地址
    const handleOk = () => {
      showAddress.value = props.list.find( item => item.id === showDialogDiv.value)
      dialogVisible.value = false
    }
    // 添加收货地址
    const formData = reactive({
      id:'',
      receiver:'',
      contact:null,
      fullLocation:'',
      address:'',
      postalCode:'',
      addressTags:'',
      provinceCode:'',
      cityCode:'',
      countyCode:''
    })
    const contactVal = (rule, value, callback) => {
      if( !/^(?:(?:\+|00)86)?1[3-9]\d{9}$/.test(value)  ){
        callback(new Error('手机号格式不正确'))
      }
      callback()
    }
    // 表单验证
    const formRule = reactive({
      receiver: [
        { required: true, message: '收货人不能为空', trigger:'blur'}
      ],
      contact: [
        { required: true, message: '手机号不能为空', trigger:'blur'},
        { validator: contactVal , trigger:'blur'}
      ],
      fullLocation: [
        { required: true, message: '地区不能为空', trigger:'blur'}
      ],
      address: [
        { required: true, message: '详细地址不能为空', trigger:'blur'}
      ],
      postalCode: [
        { required: true, message: '邮政编码不能为空', trigger:'blur'}
      ]
    })
    
    // 添加修改弹出框
    const addDialogVisible = ref(false)
    const serviceForm = ref(null)
    // 修改|添加 确定
    const handleAddOk = ()=>{
      serviceForm.value.validate( async (ok)=>{
        if(ok){
          if(formData.id){
            await editAddress(formData)
            ElMessage.success('修改成功')
            for(let key in formData){
              showAddress.value[key] = formData[key]
            }
          }else{
            await addAddress(formData)
            ElMessage.success('添加成功')
            emit('getFindCheckoutInfo')
          }
          addDialogVisible.value = false
        }
      })
    }
    // 添加地址
    const add = () => {
      addDialogVisible.value = true
      for(let key in formData){
        formData[key] = null
      }
    }
    // 修改地址
    const edit = () => {
      formData.id = showAddress.value.id
      addDialogVisible.value = true
      if(formData.id){
        for(let key in formData){
          formData[key] = showAddress.value[key]
        }
      }
    }
    // 关闭表单
    const closeForm = () => {
      serviceForm.value.resetFields()
    }
    // 选择地区
    const changeCty = (data) => {
       formData.provinceCode = data.provinceCode
      formData.cityCode = data.cityCode
      formData.countyCode = data.countyCode
      formData.fullLocation = data.fullLocation
    }
    return { showAddress, dialogVisible, handleOk, showDialogDiv, addDialogVisible, handleAddOk, add, formData, changeCty, serviceForm, formRule, closeForm, edit }
  }
}
</script>
<style scoped lang="scss">
.checkout-address {
  border: 1px solid #f5f5f5;
  display: flex;
  align-items: center;
  .dialogDiv{
    border: 1px solid #27BA9B;
    background: rgba($color: #27BA9B, $alpha: 0.1);
  }
  ::v-deep .el-form{
    width: 600px;
    margin: auto;
  }
  .city{
    width: 500px;
  }
  .text {
    flex: 1;
    min-height: 90px;
    display: flex;
    align-items: center;

    .none {
      line-height: 90px;
      color: #999;
      text-align: center;
      width: 100%;
    }

    >ul {
      flex: 1;
      padding: 20px;

      li {
        line-height: 30px;

        span {
          color: #999;
          margin-right: 5px;

          >i {
            width: 0.5em;
            display: inline-block;
          }
        }
      }
    }

    >a {
      color: $xtxColor;
      width: 160px;
      text-align: center;
      height: 90px;
      line-height: 90px;
      border-right: 1px solid #f5f5f5;
    }
  }

  .action {
    width: 420px;
    text-align: center;

    .btn {
      width: 140px;
      height: 46px;
      line-height: 44px;
      font-size: 14px;

      &:first-child {
        margin-right: 10px;
      }
    }
  }
}
</style>